package com.linkoog.devtools.utils;

import com.intellij.lang.Language;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;

public class EditorUtils {


    /**
     * create editor with specified language and content
     */
    public static  FileEditor createEditor(Project project, String languageId, String text) {
        if (isBlank(text)) {
            text = "";
        }

        Language language = Language.findLanguageByID(languageId);
        PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(language, text);
        FileEditor editor = TextEditorProvider.getInstance().createEditor(project, psiFile.getVirtualFile());
        return editor;
    }

    /**
     * set content for editor
     */
    public static  void setEditorDoc(Project project, FileEditor editor, String text) {
        if (editor == null){
            return;
        }

        WriteCommandAction.runWriteCommandAction(project, () -> {
            Document doc = getDocumentFromEditor(editor);
            doc.deleteString(0, doc.getTextLength());
            doc.setText(text == null ? "" : text.replaceAll("\\r", ""));
        });
    }

    /**
     * get content from editor
     */
    public static  String getStringFromEditor(FileEditor editor) {
        Document doc = getDocumentFromEditor(editor);
        return doc.getText();
    }

    /**
     * get document from editor
     */
    public static Document getDocumentFromEditor(FileEditor editor) {
        return FileDocumentManager.getInstance().getCachedDocument(editor.getFile());
    }

    private static boolean isBlank(CharSequence str) {
        int strLen;
        if (str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

}
